<?php

namespace app\web\controller;

use app\common\model\Store as Store_Model;
use think\Db;
use app\api\validate\Store as Store_Validate;
use app\common\model\QueueRule;
use app\api\validate\QueueRule as Queue_Rule_Validate;
use app\common\model\Order;
use app\common\model\CommissionLog;
use app\common\model\ViperUser;
use app\common\model\ViperCardRechargeLog;
use app\common\model\ViperCard;

/**
 * 库存管理--商品分类控制器
 * @package app\index\controller
 */
class Store extends Auth
{
    public $noNeedLogin = '';



    /**
     * 设置门店--获取门店详情
     */
    public function detail()
    {

        if ($this->request->isPost())
        {
            $info = Store_Model::where('id',$this->userInfo['id'])->find();

            $queue_rule =QueueRule::get(['store_id'=>$this->userInfo['id']]);

            $info['queue_type'] = isset($queue_rule)&&$queue_rule['type']==1?'大轮排':'上钟点排数';

            $this->result('获取成功',$info,200);
        }else{
            $this->result('请求错误','',204);
        }

    }

    /**
     * 设置门店--修改门店信息
     */
    public function edit()
    {
        if ($this->request->isPost())
        {
            $msg = Store_Model::where('id',$this->userInfo['store_id'])->find();
            $msg['avatar'] = get_img_path($msg['avatar']);
            $this->result('查询成功',$msg,200);
        }else{
            $this->result('请求错误','',204);
        }

    }


    /**
     * 设置门店--修改门店信息
     */
    public function save()
    {
        if ($this->request->isPost())
        {
            $data = $this->request->post();

            $validate = new Store_Validate();

            if (!$validate->check($data))
            {
                $this->result($validate->getError(),'',204);
            }
            $msg = Store_Model::where('id',$data['id'])->update($data);
            if($msg !== false){
                $this->result('操作成功','',200);
            }else{
                $this->result('操作失败','',204);
            }


        }else{
            $this->result('请求错误','',204);
        }

    }



    /**
     * 设置门店--获取门店排钟规则
     */
    public function getQueue()
    {
        if ($this->request->isPost())
        {
            $getData = $this->request->post();
            if(empty($getData['type'])){
                $this->result('缺少参数','',204);
            }
            $info = QueueRule::where('type',$getData['type'])->get(['store_id'=>$this->userInfo['store_id']]);

            $info = isset($info)?$info:[];

            $this->result('获取成功',$info,200);
        }else{
            $this->result('请求错误','',204);
        }
    }

    /**
     * 设置门店--修改排钟规则
     * queue_id  type  is_working_engineer_first
     * is_working_dot_act is_overtime_dot_act
     * is_overtime_auto_queue rule  is_overtime_act_queue
     * second_act_type is_down_act
     */
    public function queue()
    {
        $data = $this->request->post();

        $validate = new Queue_Rule_Validate();

        if (!$validate->check($data))
        {
            $this->result($validate->getError(),'',204);
        }

        if (!empty($data['id']))
        {
            $msg = QueueRule::where('id',$data['id'])->update($data);
        }else{
            $find = Db::name('qt_queue_rule')
                ->where('store_id',$this->userInfo['store_id'])->where('type',$data['type'])
                ->find();
            if(!empty($find)){
                $this->result('当前门店有排钟规则，不支持新增','',204);
            }
            $data['store_id'] = $this->userInfo['store_id'];
            $msg = QueueRule::create($data);
        }

        $msg?$this->result('更新成功','',200):$this->result('提交信息与原信息相同','',204);

    }

    /**
     * 门店业绩
     * type
     */
    public function commission()
    {
        $data = $this->request->post();

        switch ($data['type'])
        {
            case 1:
                $map = 'today';
                break;
            case 2:
                $map = 'yesterday';
                break;
            case 3:
                $map = 'month';
                break;
            case 4:
                $map = 'last month';
                break;
        }
        //营业总额
        $business_total = CommissionLog::whereTime('created_time',$map)
            ->where('store_id',$this->userInfo['id'])
            ->sum('money');
        //现金业绩
        $cash_commission = CommissionLog::where('store_id',$this->userInfo['id'])
            ->where('pay_type',1)
            ->sum('commission');
        //其他收入
        $other_income = CommissionLog::where('store_id',$this->userInfo['id'])
            ->where('pay_type','neq',1)
            ->sum('money');
        //现金消费
        $cash_expense =  Order::whereTime('created_time',$map)
            ->where('store_id',$this->userInfo['id'])
            ->where('pay_type',1)
            ->sum('money');
        //售卡业绩
        $sale_card_commission =  CommissionLog::whereTime('created_time',$map)
            ->where('store_id',$this->userInfo['id'])
            ->where('type',3)
            ->sum('commission');
        //新增会员数
        $new_user_count = ViperUser::where('create_time',$map)
            ->where('store_id',$this->userInfo['id'])
            ->count('user_id');
        //商品业绩
        $product_commission = CommissionLog::where('created_time',$map)
            ->where('store_id',$this->userInfo['id'])
            ->where('type',2)
            ->sum('commission');
        //消费人数
        $expense_number = CommissionLog::where('created_time',$map)
            ->where('store_id',$this->userInfo['id'])
            ->count('user_id');
        //人均消费
        $avg_expense = round($business_total/$expense_number,2);
        //会员消费数
        $viper_expense = CommissionLog::where('created_time',$map)
            //->leftJoin('dp_qt_user_viper v','v.id=c.user_id')
            ->where('store_id',$this->userInfo['id'])
            ->sum('money');
        //续费会员数
        $recharge_user_number = ViperCardRechargeLog::whereTime('create_time',$map)
            ->where(['store_id'=>$this->userInfo['id']])
            ->count('user_id');
        //会员赠送
        $user_give = ViperCard::whereTime('create_time',$map)
            ->where('store_id',$this->userInfo['id'])
            ->sum('give_total_amount');
        $this->result('获取成功',[
            'business_total'=>$business_total,
            'cash_commission'=>$cash_commission,
            'other_income'=>$other_income,
            'cash_expense'=>$cash_expense,
            'sale_card_commission'=>$sale_card_commission,
            'new_user_count'=>$new_user_count,
            'product_commission'=>$product_commission,
            'expense_number'=>$expense_number,
            'avg_expense'=>$avg_expense,
            'viper_expense'=>$viper_expense,
            'recharge_user_number'=>$recharge_user_number,
            'user_give'=>$user_give,
        ],200);

    }

    /**
     * 获取当前门店活动
     */
    public function activity(){
        if ($this->request->isPost()) {
            $data = Db::name('qt_data_activity')
                ->field('id,name')
                ->where(['store_id'=>$this->userInfo['store_id']])
                ->order('id desc')
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 门店提成区间设置
     */
    public function commission_list(){
        if ($this->request->isPost()) {
            $data = Db::name('qt_store_commission')
                ->field('id,start,end,money')
                ->where('store_id',$this->userInfo['store_id'])
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 门店提成区间添加
     */
    public function commission_add(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['start']) ||empty($getData['end']) || empty($getData['money']) ){
                $this->result('缺少参数', '', 204);
            }
            $getData['create_time'] = time();
            $getData['store_id'] = $this->userInfo['store_id'];
            $getData['user_id'] = $this->userInfo['id'];
            if(Db::name('qt_store_commission')->insert($getData)){
                $this->result('添加成功', '', 200);
            }
            $this->result('添加失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 门店提成区间修改
     */
    public function commission_save(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['start']) ||empty($getData['end']) || empty($getData['money']) || empty($getData['id'])){
                $this->result('缺少参数', '', 204);
            }
            if(Db::name('qt_store_commission')->where('id',$getData['id'])->update($getData)){
                $this->result('修改成功', '', 200);
            }
            $this->result('修改失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 门店提成区间删除
     */
    public function commission_remove(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少参数', '', 204);
            }
            if(Db::name('qt_store_commission')->where('id',$getData['id'])->delete()){
                $this->result('删除成功', '', 200);
            }
            $this->result('删除失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


    /*
     * 门店结算报表
     */
    public function settlement(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['start_time']) || empty($getData['end_time'])){
                $this->result('缺少时间参数', '', 204);
            }
            $startTime = strtotime($getData['start_time'].$this->storeInfo['start_time']);
            $endTime = strtotime($getData['end_time'].$this->storeInfo['end_time']);
            $sql = Db::name('qt_check_out_pay')->whereBetweenTime('create_time',$startTime,$endTime);
            $consumption = [
                'cash'=>$sql->where('pay_id','1')->where('type','2')->sum('pay_money'),//现金
                'union_pay'=>$sql->where('pay_id','2')->where('type','2')->sum('pay_money'),//微信
                'wechat_pay'=>$sql->where('pay_id','3')->where('type','2')->sum('pay_money'),//微信
                'alipay'=>$sql->where('pay_id','4')->where('type','2')->sum('pay_money'),//支付宝
                'consumer_coupon'=>$sql->where('pay_id','5')->where('type','2')->sum('pay_money'),//消费券
                'viper_card'=>$sql->where('pay_id','6')->where('type','2')->sum('pay_money'),//会员卡
            ];
            $consumption['total'] = $consumption['cash'] + $consumption['union_pay'] + $consumption['wechat_pay'] +$consumption['alipay'] +$consumption['viper_card'];
            $recharge = [
                'cash'=>$sql->where('pay_id','1')->whereIn('type',['1','3'])->sum('pay_money'),//现金
                'union_pay'=>$sql->where('pay_id','2')->whereIn('type',['1','3'])->sum('pay_money'),//微信
                'wechat_pay'=>$sql->where('pay_id','3')->whereIn('type',['1','3'])->sum('pay_money'),//微信
                'alipay'=>$sql->where('pay_id','4')->whereIn('type',['1','3'])->sum('pay_money'),//支付宝
                'consumer_coupon'=>$sql->where('pay_id','5')->whereIn('type',['1','3'])->sum('pay_money'),//消费券
                'viper_card'=>$sql->where('pay_id','6')->whereIn('type',['1','3'])->sum('pay_money'),//会员卡
            ];
            $recharge['total'] = $recharge['cash'] + $recharge['union_pay'] + $recharge['wechat_pay'] +$recharge['alipay'] + $recharge['viper_card'];
            $total = [
                'cash'=>$sql->where('pay_id','1')->sum('pay_money'),//现金
                'union_pay'=>$sql->where('pay_id','2')->sum('pay_money'),//微信
                'wechat_pay'=>$sql->where('pay_id','3')->sum('pay_money'),//微信
                'alipay'=>$sql->where('pay_id','4')->sum('pay_money'),//支付宝
                'consumer_coupon'=>$sql->where('pay_id','5')->sum('pay_money'),//消费券
                'viper_card'=>$sql->where('pay_id','6')->sum('pay_money'),//会员卡
            ];
            $total['total'] = $total['cash'] + $total['union_pay'] + $total['wechat_pay'] +$total['alipay'] + $total['viper_card'];
            $result['consumption'] = $consumption;
            $result['recharge'] = $recharge;
            $result['total'] = $total;
            $result['store_name'] = $this->storeInfo['name'];
            $result['start_time'] = date('Y-m-d H:i:s',$startTime);
            $result['end_time'] = date('Y-m-d H:i:s',$endTime);
            $result['time'] = date('Y-m-d H:i:s');
            $result['consumption_total'] = $total['total'];
            $result['no_consumption_total'] = 0;
            $result['charge'] = 0;
            //收款人
            if(empty($getData['cashier_id'])){
                $result['cashier_name'] = "所有人";
            }else{
                $userIds = explode(',',$getData['cashier_id']);
                $userNames = Db::name('qt_users')->whereIn('id',$userIds)->column('real_name');
                $result['cashier_name'] = implode(',',$userNames);
            }

            $this->result('查询成功', $result, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 用户门店列表
     */
    public function lists(){
        if ($this->request->isPost()) {
            $data = Db::name('qt_user_store')
                ->field('s.id,s.name as store_name,s.avatar,s.address')
                ->alias('us')
                ->leftJoin('qt_store s','s.id = us.store_id')
                ->where(['us.user_id'=>$this->userInfo['id']])
                ->select();
            foreach ($data as $key=>$value){
                $data[$key]['avatar'] = get_img_path($value['avatar']);
            }
            $result['store_id'] = $this->userInfo['store_id'];
            $result['data'] = $data;
            $this->result('查询成功', $result, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 切换门店
     */
    public function switch(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['store_id'])){
                $this->result('请选择门店', '', 204);
            }
            if($this->userInfo['store_id'] == $getData['store_id']){
                $this->result('切换门店和当前登录门店一致', '', 204);
            }
            $update = Db::name('qt_users')->where(['id'=>$this->userInfo['id']])->update(['store_id'=>$getData['store_id']]);
            if($update !== false){
                $this->result('切换成功', '', 200);
            }else{
                $this->result('切换门店失败', '', 204);
            }
        }
        $this->result('无效的请求', '', 204);
    }

}
